{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "60ffbcb2",
   "metadata": {},
   "source": [
    "# 单节点数据缓存\n",
    "\n",
    "[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_source.png)](https://gitee.com/mindspore/docs/blob/master/docs/programming_guide/source_zh_cn/cache.ipynb)&emsp;[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_notebook.png)](https://obs.dualstack.cn-north-4.myhuaweicloud.com/mindspore-website/notebook/master/programming_guide/mindspore_cache.ipynb)&emsp;[![](https://gitee.com/mindspore/docs/raw/master/resource/_static/logo_modelarts.png)](https://authoring-modelarts-cnnorth4.huaweicloud.com/console/lab?share-url-b64=aHR0cHM6Ly9taW5kc3BvcmUtd2Vic2l0ZS5vYnMuY24tbm9ydGgtNC5teWh1YXdlaWNsb3VkLmNvbS9ub3RlYm9vay9tb2RlbGFydHMvcHJvZ3JhbW1pbmdfZ3VpZGUvbWluZHNwb3JlX2NhY2hlLmlweW5i&imagename=MindSpore1.1.1)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b855c6fb",
   "metadata": {},
   "source": [
    "## 概述\n",
    "\n",
    "对于需要重复访问远程的数据集或需要重复从磁盘中读取数据集的情况，可以使用单节点缓存算子将数据集缓存于本地内存中，以加速数据集的读取。\n",
    "\n",
    "缓存算子依赖于在当前节点启动的缓存服务器，缓存服务器作为守护进程独立于用户的训练脚本而存在，主要用于提供缓存数据的管理，支持包括存储、查找、读取以及发生缓存未命中时对于缓存数据的写入等操作。\n",
    "\n",
    "若用户的内存空间不足以缓存所有数据集，则用户可以配置缓存算子使其将剩余数据缓存至磁盘。\n",
    "\n",
    "目前，缓存服务只支持单节点缓存，即客户端和服务器均在同一台机器上。该服务支持以下两类使用场景：\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "08910cab",
   "metadata": {},
   "source": [
    "- 缓存加载好的原始数据集\n",
    "\n",
    "    用户可以在数据集加载算子中使用缓存。这将把加载完成的数据存到缓存服务器中，后续若需相同数据则可直接从中读取，避免从磁盘中重复加载。\n",
    "\n",
    "    ![cache on leaf pipeline](https://gitee.com/mindspore/docs/raw/master/docs/programming_guide/source_zh_cn/images/cache_dataset.png)\n",
    "- 缓存经过数据增强处理后的数据\n",
    "\n",
    "    用户也可在`map`算子中使用缓存。这将允许直接缓存数据增强（如图像裁剪、缩放等）处理后的数据，避免数据增强操作重复进行，减少了不必要的计算量。\n",
    "\n",
    "    ![cache on map pipeline](https://gitee.com/mindspore/docs/raw/master/docs/programming_guide/source_zh_cn/images/cache_processed_data.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "892f9d69",
   "metadata": {},
   "source": [
    "## 缓存基础使用\n",
    "\n",
    "1.配置环境。\n",
    "\n",
    "使用缓存服务前，需要安装MindSpore，并设置相关环境变量。以Conda环境为例,设置环境如下："
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b20cfb2d",
   "metadata": {},
   "source": [
    "```bash\n",
    "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:{path_to_conda}/envs/{your_env_name}/lib/python3.7/site-packages/mindspore:{path_to_conda}/envs/{your_env_name}/lib/python3.7/site-packages/mindspore/lib\n",
    "```\n",
    "\n",
    "```bash\n",
    "export PATH=$PATH:{path_to_conda}/envs/{your_env_name}/bin\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4c3d4f1f",
   "metadata": {},
   "source": [
    "也可以用以下python设置环境"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "096b1a42",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import sys\n",
    "import mindspore\n",
    "\n",
    "python_path = \"/\".join(sys.executable.split(\"/\")[:-1])\n",
    "mindspore_path = \"/\".join(mindspore.__file__.split(\"/\")[:-1])\n",
    "mindspore_lib_path = os.path.join(mindspore_path, \"lib\")\n",
    "\n",
    "if 'PATH' not in os.environ:\n",
    "    os.environ['PATH'] = python_path\n",
    "elif python_path not in os.environ['PATH']:\n",
    "    os.environ['PATH'] += \":\" + python_path\n",
    "print(os.environ['PATH'])\n",
    "\n",
    "os.environ['LD_LIBRARY_PATH'] = \"{}:{}:{}\".format(mindspore_path, mindspore_lib_path, mindspore_lib_path.split(\"python3.7\")[0])\n",
    "print(os.environ['LD_LIBRARY_PATH'])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9d96418c",
   "metadata": {},
   "source": [
    "> 由于使用缓存可能会造成服务器的内存紧张，因此建议用户在使用缓存前增大服务器的交换内存空间至100GB以上，Ubuntu、EulerOS以及CentOS均可参考[相关教程](https://help.ubuntu.com/community/SwapFaq#How_do_I_add_a_swap_file.3F)了解如何增大交换内存空间。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "625b6519",
   "metadata": {},
   "source": [
    "2.启动缓存服务器。\n",
    "\n",
    "在使用单节点缓存服务之前，首先需要在命令行输入以下命令，启动缓存服务器："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8fc56cf5",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cache server startup completed successfully!\n",
      "The cache server daemon has been created as process id 14678 and listening on port 50052.\n",
      "\n",
      "Recommendation:\n",
      "Since the server is detached into its own daemon process, monitor the server logs (under /tmp/mindspore/cache/log) for any issues that may happen after startup\n",
      "\n"
     ]
    }
   ],
   "source": [
    "!cache_admin --start"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "379112f2",
   "metadata": {},
   "source": [
    "若输出以上信息，则表示缓存服务器启动成功。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d7260fc9",
   "metadata": {},
   "source": [
    "`cache_admin`支持以下命令和参数： \n",
    "- `--start`：启动缓存服务器，支持通过以下参数进行配置：\n",
    "    - `--workers`或`-w`：设置缓存服务器的工作线程数量，默认情况下工作线程数量为机器CPU个数的一半。该参数需要根据NUMA架构来设置，若设置值不是机器中NUMA结点数的整数倍，则缓存服务器会对其进行自动调整。\n",
    "    - `--spilldir`或`-s`：设置若缓存数据的大小超过内存空间，则溢出至磁盘的数据文件路径，默认为空（表示不启用数据溢出功能）。\n",
    "    - `--hostname`或`-h`：缓存服务器的ip地址，默认为127.0.0.1。\n",
    "    - `--port`或`-p`：缓存服务器的端口号，默认为50052。\n",
    "    - `--loglevel`或`-l`：设置日志等级，默认为1（WARNING级别）。若设置为0（INFO级别），会输出过多日志，导致性能劣化。\n",
    "- `--stop`：关闭缓存服务器。\n",
    "- `--generate_session`或`-g`：生成一个缓存会话。\n",
    "- `--destroy_session`或`-d`：删除一个缓存会话。\n",
    "- `--list_sessions`：查看当前缓存会话列表和详细信息。\n",
    "- `--server_info`：查看当前服务器配置参数及会话列表。\n",
    "- `--help`：查看帮助信息。\n",
    "\n",
    "以上命令均可使用`-h`和`-p`参数来指定服务器，用户也可通过配置环境变量`MS_CACHE_HOST`和`MS_CACHE_PORT`来指定。若未指定则默认对ip为127.0.0.1且端口号为50052的服务器执行操作。\n",
    "\n",
    "用户可通过`ps -ef|grep cache_server`命令来检查服务器是否已启动以及查询服务器参数。\n",
    "\n",
    "用户也可通过`cache_admin --server_info`命令查看服务器的详细参数列表。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "42885d85",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cache Server Configuration: \n",
      "----------------------------------------\n",
      "         config name          value\n",
      "----------------------------------------\n",
      "            hostname      127.0.0.1\n",
      "                port          50052\n",
      "   number of workers              8\n",
      "           log level              1\n",
      "           spill dir           None\n",
      "----------------------------------------\n",
      "Active sessions: \n",
      "No active sessions.\n"
     ]
    }
   ],
   "source": [
    "!cache_admin --server_info"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "099c658c",
   "metadata": {},
   "source": [
    "其中，Cache Server Configuration表格分别列出了当前服务器的IP地址、端口号、工作线程数、日志等级、溢出路径等详细配置信息。Active sessions模块展示了当前服务器中已启用的session ID列表。\n",
    "\n",
    "> - 设置cache_server初始化参数时，要先确认系统可用内存和待加载数据集大小，cache_server初始化容量或待加载数据集空间占耗超过系统可用内存时，都有可能导致机器宕机/重启、cache_server自动关闭、训练流程执行失败等问题。\n",
    "> - 若要启用数据溢出功能，则用户在启动缓存服务器时必须使用`-s`参数对溢出路径进行设置，否则该功能默认关闭。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93ff6a20",
   "metadata": {},
   "source": [
    "3.创建缓存会话。\n",
    "\n",
    "若缓存服务器中不存在缓存会话，则需要创建一个缓存会话，得到缓存会话id："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "122fd0ef",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Session created for server on port 50052: 780643335\n"
     ]
    }
   ],
   "source": [
    "!cache_admin -g"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b08d760",
   "metadata": {},
   "source": [
    "其中780643335为端口50052的服务器分配的缓存会话id，缓存会话id由服务器分配。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "fe2b5bc5",
   "metadata": {},
   "source": [
    "通过`cache_admin --list_sessions`命令可以查看当前服务器中现存的所有缓存会话信息。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d73bdcf2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Listing sessions for server on port 50052\n",
      "\n",
      "     Session    Cache Id  Mem cached Disk cached  Avg cache size  Numa hit\n",
      "   780643335         n/a         n/a         n/a             n/a       n/a\n"
     ]
    }
   ],
   "source": [
    "!cache_admin --list_sessions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "527f7c43",
   "metadata": {},
   "source": [
    "输出参数说明：\n",
    "- `Session`: 缓存会话id。\n",
    "- `Cache Id`: 当前缓存会话中的cache实例id，`n/a`表示当前尚未创建缓存实例。\n",
    "- `Mem cached`： 缓存在内存中的数据量。\n",
    "- `Disk cached`： 缓存在磁盘中的数据量。\n",
    "- `Avg cache size`：当前缓存的每行数据的平均大小。\n",
    "- `Numa hit`：Numa命中数，该值越高将获得越好的时间性能。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2666aa8c",
   "metadata": {},
   "source": [
    "4.创建缓存实例。\n",
    "\n",
    "在Python训练脚本中使用`DatasetCache` API来定义一个名为`test_cache`的缓存实例，并把上一步中创建的缓存会话id传入`session_id`参数："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "918b6680",
   "metadata": {},
   "outputs": [],
   "source": [
    "import mindspore.dataset as ds\n",
    "\n",
    "test_cache = ds.DatasetCache(session_id=780643335, size=0, spilling=False)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bee9f884",
   "metadata": {},
   "source": [
    "`DatasetCache`支持以下参数：\n",
    "- `session_id`：缓存会话的id，通过`cache_admin -g`命令来创建并获取。\n",
    "- `size`：缓存最大内存空间占用，该参数以MB为单位，例如512GB的缓存空间应设置`size=524288`，默认为0。\n",
    "- `spilling`：当内存空间超出所设置的最大内存空间占用时，是否允许将剩余的数据溢出至磁盘，默认为False。\n",
    "- `hostname`：连接至缓存服务器的ip地址，默认为127.0.0.1。\n",
    "- `port`：连接至缓存服务器的端口号，默认为50052。\n",
    "- `num_connections`：建立的TCP/IP连接数，默认为12。\n",
    "- `prefetch_size`：每次访问获取的行数，默认为20。\n",
    "\n",
    "> - 在实际使用中，通常应当首先使用`cache_admin -g`命令从缓存服务器处获得一个缓存会话id并作为`session_id`的参数，防止发生缓存会话不存在而报错的情况。\n",
    "> - 设置`size=0`代表不限制缓存所使用的内存空间，但不超过系统总内存的80%。注意，设置`size`为0可能会存在机器“out of memory”的风险，因此建议用户根据机器本身的空闲内存大小，给`size`参数设置一个合理的取值。\n",
    "> - 若设置`spilling=True`，则当内存空间不足时，多余数据将写入磁盘中。因此，用户需确保所设置的磁盘路径具有写入权限以及足够的磁盘空间，以存储溢出至磁盘的缓存数据。注意，若启动服务器时未指定溢出路径，则在调用API时设置`spilling=True`将会导致报错。\n",
    "> - 若设置`spilling=False`，则缓存服务器在耗尽所设置的内存空间后将不再写入新的数据。\n",
    "> - 当使用不支持随机访问的数据集（如`TFRecordDataset`）进行数据加载并启用缓存服务时，需要保证整个数据集均存放于本地。在该场景下，若本地内存空间不足以存放所有数据，则必须启用溢出，将数据溢出至磁盘。\n",
    "> - `num_connections`和`prefetch_size`为内部性能调优参数，一般情况下，用户无需设置这两个参数。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1a319bce",
   "metadata": {},
   "source": [
    "5.插入缓存实例。\n",
    "\n",
    "当前缓存服务既支持对原始数据集的缓存，也可以用于缓存经过数据增强处理后的数据。下例分别展示了两种使用方式。\n",
    "\n",
    "需要注意的是，两个例子均需要按照步骤4中的方法分别创建一个缓存实例，并在数据集加载或map算子中将所创建的`test_cache`作为`cache`参数分别传入。\n",
    "\n",
    "下面两个样例中使用到CIFAR-10数据集。运行样例前，需参照[数据集加载](https://www.mindspore.cn/doc/programming_guide/zh-CN/master/dataset_loading.html#cifar-10-100)中的方法下载并存放CIFAR-10数据集。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "aa3fb593",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "./datasets/cifar-10-batches-bin\n",
      "├── readme.html\n",
      "├── test\n",
      "│   └── test_batch.bin\n",
      "└── train\n",
      "    ├── batches.meta.txt\n",
      "    ├── data_batch_1.bin\n",
      "    ├── data_batch_2.bin\n",
      "    ├── data_batch_3.bin\n",
      "    ├── data_batch_4.bin\n",
      "    └── data_batch_5.bin\n",
      "\n",
      "2 directories, 8 files\n"
     ]
    }
   ],
   "source": [
    "!wget -N https://mindspore-website.obs.cn-north-4.myhuaweicloud.com/notebook/datasets/cifar-10-binary.tar.gz --no-check-certificate\n",
    "!mkdir -p datasets\n",
    "!tar -xzf cifar-10-binary.tar.gz -C datasets\n",
    "!mkdir -p datasets/cifar-10-batches-bin/train datasets/cifar-10-batches-bin/test\n",
    "!mv -f datasets/cifar-10-batches-bin/test_batch.bin datasets/cifar-10-batches-bin/test\n",
    "!mv -f datasets/cifar-10-batches-bin/data_batch*.bin datasets/cifar-10-batches-bin/batches.meta.txt datasets/cifar-10-batches-bin/train\n",
    "!tree ./datasets/cifar-10-batches-bin"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee982aa1",
   "metadata": {},
   "source": [
    "- 缓存原始数据集加载的数据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "0f72e874",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 image shape: (32, 32, 3)\n",
      "1 image shape: (32, 32, 3)\n",
      "2 image shape: (32, 32, 3)\n",
      "3 image shape: (32, 32, 3)\n"
     ]
    }
   ],
   "source": [
    "dataset_dir = \"./datasets/cifar-10-batches-bin/train\"\n",
    "\n",
    "# apply cache to dataset\n",
    "data = ds.Cifar10Dataset(dataset_dir=dataset_dir, num_samples=4, shuffle=False, num_parallel_workers=1, cache=test_cache)\n",
    "\n",
    "num_iter = 0\n",
    "for item in data.create_dict_iterator(num_epochs=1):  # each data is a dictionary\n",
    "    # in this example, each dictionary has a key \"image\"\n",
    "    print(\"{} image shape: {}\".format(num_iter, item[\"image\"].shape))\n",
    "    num_iter += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ec2d0f87",
   "metadata": {},
   "source": [
    "通过`cache_admin --list_sessions`命令可以查看当前会话有四条数据，说明数据缓存成功。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "35a12537",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Listing sessions for server on port 50052\n",
      "\n",
      "     Session    Cache Id  Mem cached Disk cached  Avg cache size  Numa hit\n",
      "   780643335  2044459912           4         n/a            3226         4\n"
     ]
    }
   ],
   "source": [
    "!cache_admin --list_sessions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8eb036c",
   "metadata": {},
   "source": [
    "- 缓存经过数据增强处理后的数据。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "c5089173",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0 image shape: (32, 32, 3)\n",
      "1 image shape: (32, 32, 3)\n",
      "2 image shape: (32, 32, 3)\n",
      "3 image shape: (32, 32, 3)\n",
      "4 image shape: (32, 32, 3)\n"
     ]
    }
   ],
   "source": [
    "import mindspore.dataset.vision.c_transforms as c_vision\n",
    "\n",
    "dataset_dir = \"./datasets/cifar-10-batches-bin/train\"\n",
    "\n",
    "# apply cache to dataset\n",
    "data = ds.Cifar10Dataset(dataset_dir=dataset_dir, num_samples=5, shuffle=False, num_parallel_workers=1)\n",
    "\n",
    "# apply cache to map\n",
    "rescale_op = c_vision.Rescale(1.0 / 255.0, -1.0)\n",
    "\n",
    "test_cache = ds.DatasetCache(session_id=780643335, size=0, spilling=False)\n",
    "\n",
    "data = data.map(input_columns=[\"image\"], operations=rescale_op, cache=test_cache)\n",
    "\n",
    "num_iter = 0\n",
    "for item in data.create_dict_iterator(num_epochs=1):  # each data is a dictionary\n",
    "    # in this example, each dictionary has a keys \"image\"\n",
    "    print(\"{} image shape: {}\".format(num_iter, item[\"image\"].shape))\n",
    "    num_iter += 1"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f072a511",
   "metadata": {},
   "source": [
    "通过`cache_admin --list_sessions`命令可以查看当前会话有五条数据，说明数据缓存成功。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "cd189b1a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Listing sessions for server on port 50052\n",
      "\n",
      "     Session    Cache Id  Mem cached Disk cached  Avg cache size  Numa hit\n",
      "   780643335   112867845           5         n/a           12442         5\n",
      "   780643335  2044459912           4         n/a            3226         4\n"
     ]
    }
   ],
   "source": [
    "!cache_admin --list_sessions"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4d243859",
   "metadata": {},
   "source": [
    "6.销毁缓存会话。\n",
    "\n",
    "在训练结束后，可以选择将当前的缓存销毁并释放内存："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "2ebbd6a2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Drop session successfully for server on port 50052\n"
     ]
    }
   ],
   "source": [
    "!cache_admin --destroy_session 780643335"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "207e7954",
   "metadata": {},
   "source": [
    "以上命令将销毁端口50052服务器中缓存会话id为1456416665的缓存。\n",
    "\n",
    "若选择不销毁缓存，则该缓存会话中的缓存数据将继续存在，用户下次启动训练脚本时可以继续使用该缓存。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5d806a3e",
   "metadata": {},
   "source": [
    "7.关闭缓存服务器。\n",
    "\n",
    "使用完毕后，可以通过以下命令关闭缓存服务器，该操作将销毁当前服务器中存在的所有缓存会话并释放内存。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "283452cc",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Cache server on port 50052 has been stopped successfully.\n"
     ]
    }
   ],
   "source": [
    "!cache_admin --stop"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1fcd17b",
   "metadata": {},
   "source": [
    "以上命令将关闭端口50052的服务器。\n",
    "\n",
    "若选择不关闭服务器，则服务器中已创建的缓存会话将保留，并供下次使用。下次训练时，用户可以新建缓存会话或重复使用已有缓存。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1ddfa67f",
   "metadata": {},
   "source": [
    "## 缓存共享\n",
    "\n",
    "对于单机多卡的分布式训练的场景，缓存算子还允许多个相同的训练脚本共享同一个缓存，共同从缓存中读写数据。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b14b21b6",
   "metadata": {},
   "source": [
    "1.启动缓存服务器。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7bf44b57",
   "metadata": {},
   "source": [
    "```bash\n",
    "$cache_admin --start\n",
    "Cache server startup completed successfully!\n",
    "The cache server daemon has been created as process id 39337 and listening on port 50052\n",
    "Recommendation:\n",
    "Since the server is detached into its own daemon process, monitor the server logs (under /tmp/mindspore/cache/log) for any issues that may happen after startup\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c9db6cb5",
   "metadata": {},
   "source": [
    "2.创建缓存会话。\n",
    "\n",
    "创建启动Python训练的Shell脚本`cache.sh`，通过以下命令生成一个缓存会话id："
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7c4aa720",
   "metadata": {},
   "source": [
    "```shell\n",
    "#!/bin/bash\n",
    "# This shell script will launch parallel pipelines\n",
    "\n",
    "# get path to dataset directory\n",
    "if [ $# != 1 ]\n",
    "then\n",
    "        echo \"Usage: sh cache.sh DATASET_PATH\"\n",
    "exit 1\n",
    "fi\n",
    "dataset_path=$1\n",
    "\n",
    "# generate a session id that these parallel pipelines can share\n",
    "result=$(cache_admin -g 2>&1)\n",
    "rc=$?\n",
    "if [ $rc -ne 0 ]; then\n",
    "    echo \"some error\"\n",
    "    exit 1\n",
    "fi\n",
    "\n",
    "# grab the session id from the result string\n",
    "session_id=$(echo $result | awk '{print $NF}')\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8d462d56",
   "metadata": {},
   "source": [
    "3.将缓存会话id传入训练脚本。\n",
    "\n",
    "继续编写Shell脚本，添加以下命令在启动Python训练时将`session_id`以及其他参数传入："
   ]
  },
  {
   "cell_type": "markdown",
   "id": "01b2fc32",
   "metadata": {},
   "source": [
    "```bash\n",
    "# make the session_id available to the python scripts\n",
    "num_devices=4\n",
    "\n",
    "for p in $(seq 0 $((${num_devices}-1))); do\n",
    "    python my_training_script.py --num_devices \"$num_devices\" --device \"$p\" --session_id $session_id --dataset_path $dataset_path\n",
    "done\n",
    "```\n",
    "\n",
    "> 直接获取完整样例代码：[cache.sh](https://gitee.com/mindspore/docs/blob/master/tutorials/tutorial_code/cache/cache.sh)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1dd505f4",
   "metadata": {},
   "source": [
    "4.创建并应用缓存实例。\n",
    "\n",
    "下面样例中使用到CIFAR-10数据集。运行样例前，需参照[数据集加载](https://www.mindspore.cn/doc/programming_guide/zh-CN/master/dataset_loading.html#cifar-10-100)中的方法下载并存放CIFAR-10数据集。目录结构如下："
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f3d6ff34",
   "metadata": {},
   "source": [
    "```text\n",
    "├─cache.sh\n",
    "├─my_training_script.py\n",
    "└─cifar-10-batches-bin\n",
    "    ├── batches.meta.txt\n",
    "    ├── data_batch_1.bin\n",
    "    ├── data_batch_2.bin\n",
    "    ├── data_batch_3.bin\n",
    "    ├── data_batch_4.bin\n",
    "    ├── data_batch_5.bin\n",
    "    ├── readme.html\n",
    "    └── test_batch.bin\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f2fd6318",
   "metadata": {},
   "source": [
    "创建并编写Python脚本`my_training_script.py`，通过以下代码接收传入的`session_id`，并在定义缓存实例时将其作为参数传入。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f5fc4e6d",
   "metadata": {},
   "source": [
    "```python\n",
    "    import argparse\n",
    "    import mindspore.dataset as ds\n",
    "\n",
    "    parser = argparse.ArgumentParser(description='Cache Example')\n",
    "    parser.add_argument('--num_devices', type=int, default=1, help='Device num.')\n",
    "    parser.add_argument('--device', type=int, default=0, help='Device id.')\n",
    "    parser.add_argument('--session_id', type=int, default=1, help='Session id.')\n",
    "    parser.add_argument('--dataset_path', type=str, default=None, help='Dataset path')\n",
    "    args_opt = parser.parse_args()\n",
    "\n",
    "    # apply cache to dataset\n",
    "    test_cache = ds.DatasetCache(session_id=args_opt.session_id, size=0, spilling=False)\n",
    "    dataset = ds.Cifar10Dataset(dataset_dir=args_opt.dataset_path, num_samples=4, shuffle=False, num_parallel_workers=1,\n",
    "                                num_shards=args_opt.num_devices, shard_id=args_opt.device, cache=test_cache)\n",
    "    num_iter = 0\n",
    "    for _ in dataset.create_dict_iterator():\n",
    "        num_iter += 1\n",
    "    print(\"Got {} samples on device {}\".format(num_iter, args_opt.device))\n",
    "```\n",
    "\n",
    "> 直接获取完整样例代码：[my_training_script.py](https://gitee.com/mindspore/docs/blob/master/tutorials/tutorial_code/cache/my_training_script.py)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f23fbbc",
   "metadata": {},
   "source": [
    "5.运行训练脚本。\n",
    "\n",
    "运行Shell脚本`cache.sh`开启分布式训练："
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6efab558",
   "metadata": {},
   "source": [
    "```bash\n",
    "$ sh cache.sh cifar-10-batches-bin/\n",
    "Got 4 samples on device 0\n",
    "Got 4 samples on device 1\n",
    "Got 4 samples on device 2\n",
    "Got 4 samples on device 3\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7d37a7ed",
   "metadata": {},
   "source": [
    "通过`cache_admin --list_sessions`命令可以查看当前会话中只有一组数据，说明缓存共享成功。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "55501b82",
   "metadata": {},
   "source": [
    "```bash\n",
    "$ cache_admin --list_sessions\n",
    "Listing sessions for server on port 50052\n",
    "\n",
    "Session    Cache Id  Mem cached Disk cached  Avg cache size  Numa hit\n",
    "3392558708   821590605          16         n/a            3227        16\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d9f9a29f",
   "metadata": {},
   "source": [
    "6.销毁缓存会话。\n",
    "\n",
    "在训练结束后，可以选择将当前的缓存销毁并释放内存："
   ]
  },
  {
   "cell_type": "markdown",
   "id": "36cfb3a7",
   "metadata": {},
   "source": [
    "```bash\n",
    "$ cache_admin --destroy_session 3392558708\n",
    "Drop session successfully for server on port 50052\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5ae2e85f",
   "metadata": {},
   "source": [
    "7.关闭缓存服务器。\n",
    "\n",
    "使用完毕后，可以选择关闭缓存服务器："
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e17d06c6",
   "metadata": {},
   "source": [
    "```bash\n",
    "$ cache_admin --stop\n",
    "Cache server on port 50052 has been stopped successfully.\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d1ef86a1",
   "metadata": {},
   "source": [
    "## 当前限制\n",
    "\n",
    "- 当前`MindDataset`、`GraphDataset`、`GeneratorDataset`、`PaddedDataset`和`NumpySlicesDataset`等数据集类不支持缓存。其中，`GeneratorDataset`、`PaddedDataset`和`NumpySlicesDataset`属于`GeneratorOp`，在不支持的报错信息中会呈现“There is currently no support for GeneratorOp under cache”。\n",
    "- 经过`batch`、`concat`、`filter`、`repeat`、`skip`、`split`、`take`和`zip`处理后的数据不支持缓存。\n",
    "- 经过随机数据增强操作（如`RandomCrop`）后的数据不支持缓存。\n",
    "- 不支持在同个数据管道的不同位置嵌套使用同一个缓存实例。\n",
    "\n",
    "## 缓存性能调优\n",
    "\n",
    "使用缓存服务能够在一些场景下获得显著的性能提升，例如：\n",
    "\n",
    "- 缓存经过数据增强处理后的数据，尤其是当数据预处理管道中包含decode等高复杂度操作时。在该场景下，用户不需要在每个epoch重复执行数据增强操作，可节省较多时间。\n",
    "- 在简单网络的训练和推理过程中使用缓存服务。相比于复杂网络，简单网络的训练耗时占比更小，因此在该场景下应用缓存，能获得更显著的时间性能提升。\n",
    "\n",
    "然而，在以下场景中使用缓存可能不会获得明显的性能收益，例如：\n",
    "\n",
    "- 系统内存不足、缓存未命中等因素将导致缓存服务在时间性能上提升不明显。因此，可在使用缓存前检查可用系统内存是否充足，选择一个适当的缓存大小。\n",
    "- 过多缓存溢出会导致时间性能变差。因此，在使用可随机访问的数据集（如`ImageFolderDataset`）进行数据加载的场景，尽量不要允许缓存溢出至磁盘。\n",
    "- 在Bert等NLP类网络中使用缓存，通常不会取得性能提升。因为在NLP场景下通常不会使用到decode等高复杂度的数据增强操作。\n",
    "- 使用non-mappable数据集（如`TFRecordDataset`）的pipeline在第一个epoch的时间开销较大。根据当前的缓存机制，non-mappable数据集需要在第一个epoch训练开始前将所有数据写入缓存服务器中，因此这使得第一个epoch时间较长。"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "MindSpore-1.1.1",
   "language": "python",
   "name": "mindspore-1.1.1"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
